<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>requestAnimationFrame</title>
	</head>
	<body>
		<div
			id="some-element-you-want-to-animate"
			style="width: 100px; height: 100px; background-color: pink"
		></div>
		<script>
			/**
			 * requestAnimationFrame(callback)
			 * 该函数会在下一次重绘更新你的动画时被调用到
			 * 这个回调函数只会传递一个参数：一个 DOMHighResTimeStamp 参数，用于表示上一帧渲染的结束时间
			 */

			const element = document.getElementById(
				'some-element-you-want-to-animate'
			);

			let start, previousTimeStamp, endAnimation;
			let done = false;

			function step(timestamp) {
				// console.log('timestamp', timestamp);
				if (start === undefined) {
					start = timestamp;
				}
				const elapsed = timestamp - start;
				// console.log('elapsed', elapsed);

				if (previousTimeStamp !== timestamp) {
					// 这里使用 Math.min() 确保元素在恰好位于 200px 时停止运动
					const count = Math.min(0.1 * elapsed, 200);
					// console.log('count', count);
					element.style.transform = `translateX(${count}px)`;
					if (count === 200) done = true;
				}

				if (elapsed < 2000) {
					// 2 秒之后停止动画
					previousTimeStamp = timestamp;
					if (!done) {
						endAnimation = window.requestAnimationFrame(step);
					}
				}
			}

			endAnimation = window.requestAnimationFrame(step);
		</script>
	</body>
</html>
